<?php

namespace App\Console\Commands;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CreateMsgSendTableCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     * [!] 建议在每月28号的凌晨一点执行
     * @example 00 01 28 * * php /www/message/artisan table-create:msg_send
     *
     * @var string
     */
    protected $signature = 'create-table:msg_send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create sub table for nice_msg_send_{Ymd} .';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handler()
    {
        $day = date('d');
        // 每月五号即可执行下一次命令
        if ($day < 5) {
            return false;
        }
        // 获取下个月的表名
        $tableName = 'nice_msg_send' . date('_Ym', time() + 28 * 86400);
        try {
            // 先检查表存在不存在
            $sql = "select count(*) from pg_class where relname = '{$tableName}'";
            $res = DB::select($sql);
            // 已存在直接跳过
            if ($res[0]->count) {
                $msg = "[".date('Y-m-d H:i:s')."][WAR] Table `{$tableName}` already exists!";
                $this->logger($msg);
                Log::info("[CMD][{$this->signature}] - " . $msg);
                return false;
            }
            // 创建数据表
            $sql = "CREATE TABLE IF NOT EXISTS {$tableName} (LIKE nice_msg_send INCLUDING ALL) INHERITS (nice_msg_send)";
            DB::select($sql);
            $msg = "[".date('Y-m-d H:i:s')."][INF] Table `{$tableName}` create successful.";
            $this->logger($msg);
            Log::info("[CMD][{$this->signature}] - " . $msg);
        } catch (\Exception $e) {
            $msg = "[".date('Y-m-d H:i:s')."][ERR][{$e->getCode()}] Table `{$tableName}` create failed! - " . $e->getMessage();
            $this->logger($msg);
            Log::info("[CMD][{$this->signature}] - " . $msg);
            return false;
        }
        return true;
    }

}
